package com.example.curvedemo.util;

import android.graphics.Canvas;
import android.os.Build;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;

/**
 * @Description:画布工具类
 * @Author: whh
 * @CreateDate: 2023/2/13 10:04
 */
public class CanvasUtils {

    public static void drawText(Canvas canvas, TextPaint paint, float x, float y, int width, int maxLine, String string) {
        drawText(canvas, paint, x, y, width, maxLine, 0, string, false);
    }

    public static void drawText(Canvas canvas, TextPaint paint, float x, float y, int width, int maxLine, String string, boolean isCenter) {
        drawText(canvas, paint, x, y, width, maxLine, 0, string, isCenter);
    }

    public static void drawText(Canvas canvas, TextPaint paint, float x, float y, int width, int maxLine, int lineSpace, String string) {
        drawText(canvas, paint, x, y, width, maxLine, lineSpace, string, false);
    }

    public static void drawText(Canvas canvas, TextPaint paint, float x, float y, int width, int maxLine, int lineSpace, String string, boolean isCenter) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            StaticLayout.Builder layoutBuilder = StaticLayout.Builder.obtain(string, 0, string.length(), paint, width);
            if (isCenter) {
                layoutBuilder.setAlignment(Layout.Alignment.ALIGN_CENTER);
            } else {
                layoutBuilder.setAlignment(Layout.Alignment.ALIGN_NORMAL);
            }
            layoutBuilder.setMaxLines(maxLine);
            layoutBuilder.setLineSpacing(ScreenUtil.sp2px(lineSpace), 1f);
            layoutBuilder.setEllipsize(TextUtils.TruncateAt.END);
            StaticLayout staticlayout = layoutBuilder.build();
            canvas.save();
            canvas.translate(x, y);
            staticlayout.draw(canvas);
            canvas.restore();
        } else {
            canvas.drawText(string, 0, string.length(), x, y, paint);
        }
    }

    /**
     * 获取文案高度
     *
     * @param paint
     * @param width
     * @param maxLine
     * @param string
     * @return
     */
    public static int getTextHeight(TextPaint paint, int width, int maxLine, int lineSpace, String string) {
        int height = 0;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            StaticLayout.Builder layoutBuilder = StaticLayout.Builder.obtain(string, 0, string.length(), paint, width);
            layoutBuilder.setAlignment(Layout.Alignment.ALIGN_NORMAL);
            layoutBuilder.setMaxLines(maxLine);
            layoutBuilder.setLineSpacing(ScreenUtil.sp2px(lineSpace), 1f);
            layoutBuilder.setEllipsize(TextUtils.TruncateAt.END);
            StaticLayout staticlayout = layoutBuilder.build();
            height = staticlayout.getHeight();
        } else {
            height = (int) (paint.descent() - paint.ascent());
        }
        return height;
    }
}
